/*
	This simple extension of the java.awt.Frame class
	contains all the elements necessary to act as the
	main window of an application.
 */

import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;

import java.awt.*;

public class sqlutil extends Frame
{
	public Connection c = null;
	public Statement stmt = null;
	
	public sqlutil(String userid, String pwd)
	{
		try {
			String connectString = "jdbc:oracle:thin:@(description=(address=(host=ragnall.ee.pitt.edu)(protocol=tcp)(port=1521))(connect_data=(sid=J7)))";
			DriverManager.registerDriver(new OracleDriver());
			c = DriverManager.getConnection(connectString,userid,pwd);
			c.setAutoCommit(true);
			stmt = c.createStatement();
		}
		catch(Exception e) {
            System.out.println(e.getMessage());
            System.exit(1);
		}
		// This code is automatically generated by Visual Cafe when you add
		// components to the visual environment. It instantiates and initializes
		// the components. To modify the code, only use code syntax that matches
		// what Visual Cafe can generate, or Visual Cafe may be unable to back
		// parse your Java file into its visual environment.
		
		//{{INIT_CONTROLS
		setLayout(null);
		setBackground(java.awt.Color.lightGray);
		setSize(492,300);
		setVisible(false);
		add(queryField);
		queryField.setBounds(12,12,384,24);
		queryButton.setLabel("Query");
		add(queryButton);
		queryButton.setBounds(408,12,72,24);
		add(executeField);
		executeField.setBounds(12,48,384,24);
		executeButton.setLabel("Execute");
		add(executeButton);
		executeButton.setBounds(408,48,72,24);
		resultArea.setEditable(false);
		add(resultArea);
		resultArea.setFont(new Font("MonoSpaced", Font.PLAIN, 10));
		resultArea.setBounds(12,84,468,204);
		setTitle("DataBase Application");
		//}}
		
		//{{INIT_MENUS
		//}}
		
		//{{REGISTER_LISTENERS
		SymWindow aSymWindow = new SymWindow();
		this.addWindowListener(aSymWindow);
		SymAction lSymAction = new SymAction();
		queryButton.addActionListener(lSymAction);
		executeButton.addActionListener(lSymAction);
		//}}
	}
	
	public sqlutil(String title, String userid, String pwd)
	{
		this(userid,pwd);
		setTitle(title);
	}
	
    /**
     * Shows or hides the component depending on the boolean flag b.
     * @param b  if true, show the component; otherwise, hide the component.
     * @see java.awt.Component#isVisible
     */
    public void setVisible(boolean b)
	{
		if(b)
		{
			setLocation(50, 50);
		}	
		super.setVisible(b);
	}
	
	static public void main(String args[])
	{
		try
		{
			//Create a new instance of our application's frame, and make it visible.
    		(new sqlutil(args[0],args[1])).setVisible(true);
		}
		catch (Throwable t)
		{
			System.err.println(t);
			t.printStackTrace();
			//Ensure the application exits with an error condition.
			System.exit(1);
		}
	}
	
	public void addNotify()
	{
		// Record the size of the window prior to calling parents addNotify.
		Dimension d = getSize();
		
		super.addNotify();
	
		if (fComponentsAdjusted)
			return;
	
		// Adjust components according to the insets
		setSize(getInsets().left + getInsets().right + d.width, getInsets().top + getInsets().bottom + d.height);
		Component components[] = getComponents();
		for (int i = 0; i < components.length; i++)
		{
			Point p = components[i].getLocation();
			p.translate(getInsets().left, getInsets().top);
			components[i].setLocation(p);
		}
		fComponentsAdjusted = true;
	}
	
	// Used for addNotify check.
	boolean fComponentsAdjusted = false;
	
	//{{DECLARE_CONTROLS
	java.awt.TextField queryField = new java.awt.TextField();
	java.awt.Button queryButton = new java.awt.Button();
	java.awt.TextField executeField = new java.awt.TextField();
	java.awt.Button executeButton = new java.awt.Button();
	java.awt.TextArea resultArea = new java.awt.TextArea();
	//}}
	
	//{{DECLARE_MENUS
	//}}
	
	class SymWindow extends java.awt.event.WindowAdapter
	{
		public void windowClosing(java.awt.event.WindowEvent event)
		{
			Object object = event.getSource();
			if (object == sqlutil.this)
				sqlutil_WindowClosing(event);
		}
	}
	
	void sqlutil_WindowClosing(java.awt.event.WindowEvent event)
	{
		// to do: code goes here.
		this.setVisible(false);
		try {
		    stmt.close();
		    c.close();
		}
		catch(SQLException sqle) {
		}
		System.exit(0);
	}

	
	class SymAction implements java.awt.event.ActionListener
	{
		public void actionPerformed(java.awt.event.ActionEvent event)
		{
			Object object = event.getSource();
			if (object == queryButton)
				queryButton_ActionPerformed(event);
			else if (object == executeButton)
				executeButton_ActionPerformed(event);
			
		}
	}


	void queryButton_ActionPerformed(java.awt.event.ActionEvent event)
	{
		// to do: code goes here.
		ResultSet r = null;
		boolean success = false;
		int columns = 0;
		try {
		    r = stmt.executeQuery(queryField.getText());
		    columns = r.getMetaData().getColumnCount();
		    String s = "";
		    for(int i=0; i<columns; i++) {
		        String t = r.getMetaData().getColumnName(i+1);
		        int size = r.getMetaData().getColumnDisplaySize(i+1);
		        if(t.length() < size) {
		            int l = t.length();
		            for(int j=0; j<size-l; j++) {
		                t = t + " ";
		            }
		        }
		        s = s + t;
		        if(i != (columns-1)) s = s + "  ";
		    }
		    success = true;
		    resultArea.append(s + '\n');
            /*for(int i=0; i<s.length(); i++)
                resultArea.append("-");
            resultArea.append("\n");*/
		}
		catch(SQLException sqle) {
		    resultArea.append(sqle.getMessage() + "\n\n");
		}
		if(success) {
		    String s = "";
		    try {
		        while(r.next()) {
		            for(int i=0; i<columns; i++) {
		                String t = r.getString(i+1);
		                int size = r.getMetaData().getColumnDisplaySize(i+1);
		                if(t.length() < size){
		                    int l = t.length();
		                    for(int j=0; j<size-l; j++){
		                        t = t + " ";
		                    }
		                }
		                s = s + t;
		                if(i != (columns-1)) s = s + "  ";
		            }
		            s = s + '\n';
		        }
		        resultArea.append(s + '\n');
		    }
		    catch(SQLException sqle) {
		        resultArea.append(sqle.getMessage() + "\n\n");
		    }
		}
		//queryButton_ActionPerformed_Interaction1(event);
	}

	void queryButton_ActionPerformed_Interaction1(java.awt.event.ActionEvent event)
	{
		try {
			// queryField Clear the text for TextField
			queryField.setText("");
		} catch (Exception e) {
		}
	}

	void executeButton_ActionPerformed(java.awt.event.ActionEvent event)
	{
		// to do: code goes here.
		boolean result = false;
		try {
		    result = stmt.execute(executeField.getText());
    		if(result) {
		        //ResultSet
    		    resultArea.append("ResultSet returned\n\n");
	    	}
		    else {
		        //getUpdateCount
		        resultArea.append("Modified " + stmt.getUpdateCount() + " record(s)\n\n");
		    }
		}
		catch(SQLException sqle) {
		    resultArea.append(sqle.getMessage() + "\n\n");
	    }
		//executeButton_ActionPerformed_Interaction1(event);
	}

	void executeButton_ActionPerformed_Interaction1(java.awt.event.ActionEvent event)
	{
		try {
			// executeField Clear the text for TextField
			executeField.setText("");
		} catch (Exception e) {
		}
	}
}

